﻿import wx
import userdoc

class MyTreeCtrl(wx.TreeCtrl):
  def __init__(self, parent, userdoc):       
    wx.TreeCtrl.__init__(self, parent)
    il = wx.ImageList(16,16)
    self.userdoc = userdoc
    self.fldridx = il.Add(
            wx.ArtProvider.GetBitmap(wx.ART_FOLDER, 
                    wx.ART_OTHER, (16,16)))
    self.fldropenidx = il.Add(
            wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN,   
                    wx.ART_OTHER, (16,16)))
    self.fileidx = il.Add(
            wx.ArtProvider.GetBitmap(wx.ART_NORMAL_FILE, 
                    wx.ART_OTHER, (16,16)))   
    self.AssignImageList(il)
    root = self.AddRoot(userdoc.account)
    self.SetItemImage(root, self.fldridx,wx.TreeItemIcon_Normal)
    self.SetItemImage(root, self.fldropenidx,wx.TreeItemIcon_Expanded)
    self.ShowFolderItems(root, 'root')
    
    self.Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDClick)
    
  def ShowFolderItems(self, parentItem, resource_id):
    child_resource_id_list = self.userdoc.doc_folder_dict[resource_id]
    if len(child_resource_id_list) == 0:
      return
    unfolder_list = []
    # show folder first
    for child_resource_id in child_resource_id_list:
      doc_info = self.userdoc.doc_dict[child_resource_id]
      print 'item name:', doc_info.name
      print 'resource id', doc_info.resource_id
      if doc_info.doc_type == 'folder':
        newItem = self.AppendItem(parentItem, doc_info.name)
        self.SetItemImage(newItem, self.fldridx,wx.TreeItemIcon_Normal)
        self.SetItemImage(newItem, self.fldropenidx,wx.TreeItemIcon_Expanded)   
        #self.AppendItem(newItem, 'docinfoname')        
        doc_info.set_item(newItem, parentItem)
      else:
        unfolder_list.append(doc_info)          
    # show not-folder doc after folder
    for doc_info in unfolder_list:
      newItem = self.AppendItem(parentItem, doc_info.name)
      self.SetItemImage(newItem, self.fileidx,wx.TreeItemIcon_Normal)
      doc_info.set_item(newItem, parentItem)
    self.Expand(parentItem)
    
  def OnLeftDClick(self, event):
    pos = event.GetPosition();
    item, flags = self.HitTest(pos)
    
    if item:
      item_name = self.GetItemText(item)
      parent_item = self.GetItemParent(item)
      doc_info = self.userdoc.GetResourceIdByItemName(item_name, parent_item)
      if doc_info.doc_type == 'folder':
        print "OnLeftDClick: ", item_name
        print 'resource id:', doc_info.resource_id
        self.userdoc.GetFolder(doc_info)        
        self.ShowFolderItems(item, doc_info.resource_id)
      else:
        print 'type is: ', doc_info.doc_type
        self.userdoc.GetDocument(doc_info)
      